package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.SysCustomer;
import com.example.service.SysCustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private SysCustomerService sysCustomerService;

    @Cacheable(value = "CustomerList")
    @RequestMapping("/list")
    public String listCustomer(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize, Map map) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysCustomer> list = sysCustomerService.list();
        PageInfo pageInfo = new PageInfo<>(list);
        map.put("pageInfo", pageInfo);
        map.put("pageNum", pageNum);
        return "/system/customer/customerlist";
    }

    @RequestMapping("/save.do")
    public String addCustomer(SysCustomer sysCustomer) {
        sysCustomerService.save(sysCustomer);
        return "redirect:/customer/list";
    }

    @RequestMapping("/edit.do")
    public String editCustomer(Integer id, Map map) {
        SysCustomer customer = sysCustomerService.getById(id);
        map.put("customer", customer);
        return "/system/customer/customeredit";
    }

    @RequestMapping("/update.do")
    public String updateCustomer(SysCustomer sysCustomer) {
        log.info(sysCustomer.toString());
        sysCustomerService.updateById(sysCustomer);
        return "redirect:/customer/list";
    }

    @RequestMapping("/delete.do")
    public String deleteCustomer(Integer id) {
        sysCustomerService.removeById(id);
        return "redirect:/customer/list";
    }

    @RequestMapping("/select.do")
    public String selectCustomer(@RequestParam(defaultValue = "1") Integer pageNum
            , @RequestParam(defaultValue = "3") Integer pageSize, String customerName, Map map) {
        QueryWrapper<SysCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", customerName);
        List<SysCustomer> list = sysCustomerService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo<>(list);
        map.put("pageInfo", pageInfo);
        map.put("pageNum", pageNum);
        return "/system/customer/customerlist";
    }
}
